package repo

import (
	"time"

	"github.com/star-find-cloud/star-chat/user/domain"
)

type userDB struct {
	ID             int64            `db:"id"`
	Name           string           `db:"name"`
	NickName       string           `db:"nick_name"`
	Password       string           `db:"password"`
	Email          string           `db:"email"`
	CountryCode    int64            `db:"country_code"` // CountryCode 标识电话号码所在国家
	Phone          int64            `db:"phone"`        // Phone 电话号码
	Sex            int64            `db:"sex"`
	Avatar         int64            `db:"avatar"`
	Tags           map[string]int64 `db:"tags"`
	Status         int64            `db:"status"`
	LastIP         string           `db:"last_ip"`
	VipStatus      int64            `db:"vip_status"`
	VipExpiredTime time.Time        `db:"vip_expired_time"`
	CreateTime     time.Time        `db:"create_time"`
	UpdateTime     time.Time        `db:"update_time"`
	DeleteTime     time.Time        `db:"delete_time"`
}

// timeToUnix 将time.Time转换为Unix时间戳，处理零值
func timeToUnix(t time.Time) int64 {
	if t.IsZero() {
		return 0
	}
	return t.Unix()
}

// toDomainUser 将数据库模型转换为领域模型
func toDomainUser(dbUser *userDB) *domain.User {
	if dbUser == nil {
		return nil
	}
	
	return &domain.User{
		ID:             dbUser.ID,
		Name:           dbUser.Name,
		NickName:       dbUser.NickName,
		Password:       dbUser.Password,
		Email:          dbUser.Email,
		CountryCode:    dbUser.CountryCode,
		Phone:          dbUser.Phone,
		Sex:            dbUser.Sex,
		Avatar:         dbUser.Avatar,
		Tags:           dbUser.Tags,
		Status:         dbUser.Status,
		LastIP:         dbUser.LastIP,
		VipStatus:      dbUser.VipStatus,
		VipExpiredTime: timeToUnix(dbUser.VipExpiredTime),
		CreateTime:     timeToUnix(dbUser.CreateTime),
		UpdateTime:     timeToUnix(dbUser.UpdateTime),
		DeleteTime:     timeToUnix(dbUser.DeleteTime),
	}
}

// unixToTime 将Unix时间戳转换为time.Time，处理零值
func unixToTime(timestamp int64) time.Time {
	if timestamp == 0 {
		return time.Time{}
	}
	return time.Unix(timestamp, 0)
}

// toDBUser 将领域模型转换为数据库模型
func toDBUser(user *domain.User) *userDB {
	if user == nil {
		return nil
	}
	
	return &userDB{
		ID:             user.ID,
		Name:           user.Name,
		NickName:       user.NickName,
		Password:       user.Password,
		Email:          user.Email,
		CountryCode:    user.CountryCode,
		Phone:          user.Phone,
		Sex:            user.Sex,
		Avatar:         user.Avatar,
		Tags:           user.Tags,
		Status:         user.Status,
		LastIP:         user.LastIP,
		VipStatus:      user.VipStatus,
		VipExpiredTime: unixToTime(user.VipExpiredTime),
		CreateTime:     unixToTime(user.CreateTime),
		UpdateTime:     unixToTime(user.UpdateTime),
		DeleteTime:     unixToTime(user.DeleteTime),
	}
}
